/*
 * Copyright 2020-2030 the original author or authors.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      https://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package com.gitee.minimalismstyle.fresh.common.security.util

import com.gitee.minimalismstyle.fresh.common.core.const.CacheConst
import com.gitee.minimalismstyle.fresh.common.core.domain.Context
import com.gitee.minimalismstyle.fresh.common.security.domain.FreshGrantedAuthority
import com.gitee.minimalismstyle.fresh.common.security.domain.FreshUserDetails
import org.springframework.security.core.context.SecurityContextHolder

/**
 *  获取权限上下文工具类
 * @author maoxiaodong
 */
object SecurityContextUtils {

    /**
     *  当前用户
     */
    fun user(): FreshUserDetails {
        val ctx = SecurityContextHolder.getContext()
        val auth = ctx.authentication
        val principal = auth?.principal
        return if (principal != null) {//优先从spring Security中获取
            when (principal) {
                is FreshUserDetails -> {
                    principal
                }
                is Map<*, *> -> {
                    FreshUserDetails(
                        id = principal["id"].toString().toLong(),
                        username = principal["username"].toString(),
                        tenantId = principal["tenantId"].toString().toLong(),
                        groupId = principal["groupId"].toString().toLong(),
                        authorities =  auth.authorities as Collection<FreshGrantedAuthority>
                    )
                }
                else -> {
                    FreshUserDetails()
                }
            }

        } else {//从应用上下文获取，不一定能获取到
            val user = Context.get(CacheConst.USER_INFO_KEY)
            if (user != null && user is FreshUserDetails) {
                user
            } else {
                FreshUserDetails()
            }
        }

    }
}
